<template>
    <div class="select1">
        <el-header class="header">  
            <el-menu mode="horizontal" default-active="1">  
            <el-menu-item @click="f4()" :class="{ active: isSelect }" style="font-size: 25px !important;">直达</el-menu-item>  
            <el-menu-item @click="f5()" :class="{ active: isSelect1 }" style="font-size: 25px !important;">中转</el-menu-item>  
            </el-menu>  
        </el-header> 
        <br>
        
        <div class="aligned-title">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item label="排序方式">
            <el-select
              placeholder="请选择排序方式"
              v-model="sort"
              clearable>
              <el-option label="时间最短" :value=1 />
              <el-option label="价格最低" :value=2 />
              <el-option label="时间最长" :value=3 />
              <el-option label="价格最高" :value=4 />
            </el-select>
          </el-form-item>
        </el-form>
          <el-table :data="formattedFlights"  border style="width: 100%; margin-top: 20px">  
          <el-table-column label="航空公司/航班名称" width="200">  
            <template v-slot="slotProps1">  
              <div>  
                {{ slotProps1.row.startAirlineCompany }}<br>  
                {{ slotProps1.row.startFlightName }}  
              </div>  
            </template>  
          </el-table-column>  
          <el-table-column label="起始时间/机场" width="200">  
            <template v-slot="slotProps1">  
              <div>  
                {{ extractTime(slotProps1.row.firstFlightTime) }}<br>  
                {{ slotProps1.row.startAirport }}  
              </div>  
            </template>  
          </el-table-column> 
          <el-table-column label="中转" width="180"> 
            <template v-slot="scope">
              <div class="image-button-container">
                <img src="./image/2.png" width="80px">
                <el-button plain @click="open(scope.row)" style="background-color: #0086f6 !important;">查看详情</el-button>
              </div>
            </template> 
          </el-table-column>
          <el-table-column label="终止时间/机场" width="200">  
            <template v-slot="slotProps1">  
              <div>  
                {{ extractTime(slotProps1.row.lastFlightTime) }}<br>  
                {{ slotProps1.row.endAirport }}  
              </div>  
            </template>  
          </el-table-column> 
          <el-table-column label="总时间" width="200">  
            <template v-slot="slotProps1">  
              <div>  
                {{ slotProps1.row.totalDuration }}  
              </div>  
            </template>  
          </el-table-column>
          <el-table-column prop="totalPrice" label="价格" width="200"/>  
          <el-table-column label="">
              <template v-slot="scope">  
                  <el-button plain @click="buy(scope.row)" style="background-color: #0086f6 !important;">购买</el-button>  
              </template>
          </el-table-column>
        </el-table>  
        <el-dialog v-model="dialogVisible" title="请确认航班信息" width="1000" @close="beforeClose()">
              <span>
                  <el-table :data="tableData" class="no-border-table">
                      <el-table-column prop="selectedDate"></el-table-column>
                      <el-table-column>  
                          <template v-slot="slotProps1">  
                              <div>{{ getWeekday(slotProps1.row.selectedDate) }}</div>  
                          </template>  
                      </el-table-column>
                      <el-table-column prop="departureCity"></el-table-column>
                      <el-table-column>
                          <template #default="scope">  
                              <el-icon><Right /></el-icon>  
                          </template></el-table-column>
                      <el-table-column prop="destination"></el-table-column>
                  </el-table>
                  <el-table :data="tableData1" class="no-border-table">
                      <el-table-column prop="airlineCompany"></el-table-column>
                      <el-table-column prop="airlineName"></el-table-column>
                  </el-table>
                  <el-table :data="tableData1" class="no-border-table">
                      <el-table-column>
                        <template v-slot="slotProps1">  
                          <div>{{ extractTime(slotProps1.row.startTime) }}</div>  
                          <div>{{ slotProps1.row.startAirport }}</div>
                        </template> 
                      </el-table-column>
                      <el-table-column>
                        <template v-slot="slotProps1">  
                          {{ calculateTimeDifference(slotProps1.row.startTime,slotProps1.row.arriveTime) }}
                        </template> 
                      </el-table-column>
                      <el-table-column>
                        <template v-slot="slotProps1">  
                          <div>{{ extractTime(slotProps1.row.arriveTime) }}</div>  
                          <div>{{ slotProps1.row.arriveAirport }}</div>
                        </template> 
                      </el-table-column>
                  </el-table>
                  <el-table :data="tableData1" class="no-border-table">
                    <el-table-column>价格：</el-table-column>
                    <el-table-column prop="price"/>
                  </el-table>
                  <el-form-item label="位置偏好">
                    <el-radio-group v-model="seat">
                        <el-radio value=1>过道</el-radio>
                        <el-radio value=2>中间</el-radio>
                        <el-radio value=3>窗边</el-radio>
                    </el-radio-group>
                  </el-form-item>
                  <el-form-item label="乘车人">
                    <el-checkbox-group v-model="selectedPassenger">  
                      <span v-for="(item, index) in passenger" :key="index">  
                        <label>  
                          <el-checkbox :value="index" style="margin-right: 20px;">{{ item.name }}</el-checkbox> <!-- 注意此处的 v-model  -->  
                        </label>  
                      </span>  
                    </el-checkbox-group>  
                  </el-form-item>
              </span>
              <template #footer>
                  <div class="dialog-footer">
                      <el-button @click="beforeClose()" style="background-color: #0086f6 !important; color: white !important;">取消</el-button>
                      <el-button type="primary" @click="submit(tableData1)" style="background-color: #0086f6 !important; color: white !important;">提交</el-button>
                  </div>
              </template>
          </el-dialog>
          <el-dialog v-model="dialogVisible1" title="航班详细信息" width="700">
              <div>
                {{ condition.departureCity }}
                <el-icon><Right /></el-icon> 
                {{ condition.destination }}&nbsp;&nbsp;&nbsp;&nbsp;
                总时长{{ calculateTimeDifference(detal.rows[0].flight.startTime,detal.rows[detal.rows.length-1].flight.arriveTime) }}
              </div><hr>
              <div v-for="(stu,index) in detal.rows" :key="index">
                <p>
                  {{ stu.flight.airlineCompany }}&nbsp;&nbsp;&nbsp;&nbsp;
                  {{ stu.flight.airlineName }}
                </p>
                <p>
                  {{ stu.flight.startTime }}&nbsp;&nbsp;&nbsp;&nbsp;
                  {{ stu.flight.startAirport }}
                </p>
                <p>
                  <el-icon><Bottom /></el-icon>
                  飞行{{ calculateTimeDifference(stu.flight.startTime,stu.flight.arriveTime) }}
                </p>
                <p>
                  {{ stu.flight.arriveTime }}&nbsp;&nbsp;&nbsp;&nbsp;
                  {{ stu.flight.arriveAirport }}
                </p>
                <p v-if="index !== detal.rows.length - 1">
                  <hr>
                  <!-- {{ getCity(detal.rows[index].flight.arriveAirport)  }} -->
                  {{ city[index] }}
                  停留{{ calculateTimeDifference(detal.rows[index].flight.arriveTime,detal.rows[index+1].flight.startTime) }}
                  <hr>
                </p>
              </div>
          </el-dialog>
      </div>
    </div>
</template>

<script setup lang="ts" name="Select1">
// 从 Element Plus 导入需要的组件  
import { ElButton, ElIcon } from 'element-plus';  
// 从 Element Plus 图标库中导入特定图标  
import { Right,Bottom } from '@element-plus/icons-vue'; 
import {ref,reactive, onMounted} from 'vue';
import {watch,computed} from 'vue';
import { useRouter } from 'vue-router';
import {useRoute} from 'vue-router';
import axios from 'axios';
import { ElMessage } from 'element-plus'; 
const route=useRoute();
const router = useRouter();
//数据
const isSelect = computed(() => route.path === '/select');  
const isSelect1 = computed(() => route.path === '/select1');  
const data = JSON.parse(route.query.order as string); 
let sort=ref<number>(1);
let seat=ref<number>(0);
let dialogVisible=ref<boolean>(false);
let dialogVisible1=ref<boolean>(false);
class Tickets {
  airlineCompany:string;//航天公司
  airlineName:string;//航班名称
  startTime:string;//出发时间
  startAirport:string;//出发机场
  arriveTime:string;//到达时间
  arriveAirport:string;//到达机场
  price:number;//价格

  constructor(startTime:string,startAirport:string,arriveTime:string,arriveAirport:string,airlineCompany:string,airlineName:string,price:number)
  {
    this.startTime=startTime,
    this.startAirport=startAirport,
    this.arriveTime=arriveTime,
    this.arriveAirport=arriveAirport,
    this.airlineCompany=airlineCompany,
    this.airlineName=airlineName,
    this.price=price
  }
}
// 定义中转航班的接口  
interface FlightTransfer {   
  rows: FlightLeg[]; // 航班段  
} 
// 定义航班段的接口  
interface FlightLeg {  
  flight: Tickets; // 航班信息  
}  
class Condition{
    airlineCompany:string="";//航天公司
    airport:string="";//机场
    departureCity:string="";//出发城市
    destination:string="";//目的城市
    selectedDate:string="";//旅行日期
    peopleNum:number=0;//出行人数
    
    constructor(airlineCompany:string,airport:string,departureCity:string,destination:string,selectedDate:string,peopleNum:number){
        this.airlineCompany=airlineCompany;
        this.airport=airport;
        this.departureCity=departureCity;
        this.destination=destination;
        this.selectedDate=selectedDate;
        this.peopleNum=peopleNum;
    }
}
const condition =new Condition(data.airlineCompany,
                        data.airport,
                        data.departureCity,
                        data.destination,
                        data.selectedDate,
                        data.peopleNum);
const tableData = ref([condition]);
const tableData1 = ref<Tickets[]>([]); 
const tickets: FlightTransfer[] = reactive([]);
// let t1:Tickets={
//     airlineCompany:"东方航空",
//     airlineName:"MU2615",
//     startTime:"2024-11-11T12:00:00Z",
//     startAirport:"天河国际机场",
//     arriveTime:"2024-11-11T12:10:00Z",
//     arriveAirport:"成田国际机场",
//     price:520
// };
// let t2:Tickets={
//     airlineCompany:"中国国航",
//     airlineName:"MU1111",
//     startTime:"2024-11-11T15:00:00Z",
//     startAirport:"成田国际机场",
//     arriveTime:"2024-11-11T19:20:00Z",
//     arriveAirport:"黄花国际机场",
//     price:250
// }; 
// let t3: Tickets = {  
//   airlineCompany: "海南航空",  
//   airlineName: "HU1234",  
//   startTime: "2024-11-11T08:00:00Z",   
//   startAirport: "黄花国际机场",  
//   arriveTime: "2024-11-11T12:30:00Z",   
//   arriveAirport: "上海浦东国际机场",  
//   price: 300,  
// };  
// let t4: Tickets = {  
//   airlineCompany: "南方航空",  
//   airlineName: "CZ5678",  
//   startTime: "2024-11-11T15:00:00Z",  
//   startAirport: "上海浦东国际机场",  
//   arriveTime: "2024-11-11T21:30:00Z",   
//   arriveAirport: "成都双流国际机场",  
//   price: 250,   
// };  
// let t5: Tickets = {  
//   airlineCompany: "深圳航空",  
//   airlineName: "ZH9101",  
//   startTime: "2024-11-12T07:00:00Z",  
//   startAirport: "成都双流国际机场",  
//   arriveTime: "2024-11-12T15:00:00Z",  
//   arriveAirport: "天河国际机场",  
//   price: 200,  
// };
// tickets.push({    
//   rows: [  
//     { flight: t1 },  
//     { flight: t2 },  
//   ],  
// }); 
// tickets.push({    
//   rows: [  
//     { flight: t3 }, 
//     { flight: t4 },   
//     { flight: t5 }  
//   ],  
// }); 
// console.log(tickets);
const params = {  
  departCity:condition.departureCity,
  arriveCity:condition.destination,
  peoNumber:condition.peopleNum,
  day:condition.selectedDate 
}; 
axios.get('http://localhost:8080/turnFlight',{params})
    .then((response) => {
        // console.log(response.data.data);
        // 请求成功，将返回的数据显示在页面上
        response.data.data.rows.forEach((flightTransfer) => {  
          // 创建一个新的 FlightTransfer 对象  
          const newFlightTransfer: FlightTransfer = {  
            rows: [] // 初始化一个空的 rows 数组  
        };  
        // 遍历每个航班段  
        flightTransfer.forEach((item) => {  
          // 创建一个新的航班信息对象并推入新的 rows 数组  
          newFlightTransfer.rows.push({  
            flight: new Tickets(  
              item.departTime + "Z", // 出发时间  
              item.departAName,      // 出发机场  
              item.arrivalTime + "Z", // 到达时间  
              item.arrivalAName,     // 到达机场  
              item.cname,            // 航空公司名称  
              item.fnumber,          // 航班号  
              item.price             // 价格  
            )  
          });  
        });  
        // 将新的 FlightTransfer 对象推入 tickets 数组  
        tickets.push(newFlightTransfer);  
      });  
    })
    .then(()=>{
      tickets.splice(0, tickets.length, ...sortTickets(1));
      // console.log(tickets);
})
const formattedFlights = computed(() => {  
  return tickets.map((transfer, index) => {  // 添加 index 参数  
    const legs = transfer.rows.map(leg => leg.flight);  
    const firstFlightTime = legs[0].startTime; // 第一个航班的起始时间  
    const lastFlightTime = legs[legs.length - 1].arriveTime; // 最后一个航班的结束时间  
    // 计算总时间  
    const totalDuration = Math.abs(new Date(lastFlightTime).getTime() - new Date(firstFlightTime).getTime());  
    const totalDurationHours = Math.floor(totalDuration / (1000 * 60 * 60)); // 转换为小时  
    const totalDurationMinutes = Math.floor((totalDuration % (1000 * 60 * 60)) / (1000 * 60)); // 转换为分钟  
    // 优化显示总时间  
    let totalDurationString = '';  
    if (totalDurationHours > 0) {  
      totalDurationString += `${totalDurationHours}小时`;  
    }  
    if (totalDurationMinutes > 0 || totalDurationHours === 0) { // 如果小时为0，分钟也要显示  
      totalDurationString += `${totalDurationMinutes}分钟`;  
    }  
    const startAirlineCompany = legs[0].airlineCompany; // 获取起始航空公司  
    const startFlightName = legs[0].airlineName; // 获取起始航班名称  
    const totalPrice = legs.reduce((sum, leg) => sum + leg.price, 0); // 计算总价格  
    const startAirport = legs[0].startAirport; // 起始机场  
    const endAirport = legs[legs.length - 1].arriveAirport; // 最后航班的到达机场  
    return {  
      index,  // 添加 index 属性  
      firstFlightTime,  
      lastFlightTime,  
      totalDuration: totalDurationString,  
      startAirlineCompany,  
      startFlightName,  
      totalPrice,  
      startAirport,  
      endAirport,  
    };  
  });  
});
class Passenger{
    name:string="";//姓名
    sex:number;//性别
    idType:string="中国居民身份证";//证件类型
    idNumber:string="";//证件号码
    phone:string="";//电话号码

    constructor(name:string,gender:number,idNum:string,telNum:string){
        this.name=name;
        this.sex=gender;
        this.idNumber=idNum;
        this.phone=telNum;
    }

    mask():string{
        const maskedStr = `${this.idNumber.slice(0,2)}**************${this.idNumber.slice(16)}`;
        return maskedStr;
    }
  }
let passenger: Passenger[]=reactive([]);
let selectedPassenger=ref<number[]>([]);
const username = route.query.account;
const url1 = `http://localhost:8080/passenger/${username}`;
getPassenger();
//方法
class Order{
  fnumber:string;
  sort:number;
  seat:number;

  constructor(fn:string,so:number,se:number){
    this.fnumber=fn;
    this.sort=so;
    this.seat=se;
  }
}
function submit(m){
  // console.log(seat.value);
  // console.log(m[0].airlineName);
  console.log(tickets[nowIndex.value].rows.length-1);
  let orders: Order[] = [];  
  orders.push(new Order(m[0].airlineName,tickets[nowIndex.value].rows.length-1,seat.value));
  selectedPassenger.value.forEach(item=>{
    const params={
      idNumList: passenger[item].idNumber
    }
    axios.post('http://localhost:8080/order', orders, {params})  
    .then((response) => {
                  if(response.data.code==1)
                    ElMessage.success({message:response.data.msg,showClose:true});
                  else
                    ElMessage.error({message:response.data.msg,showClose:true});
                    beforeClose();
              })
  })
}
function getPassenger(){
    passenger.length=0;
    axios.get(url1)
    .then((response) => {
        response.data.data.forEach(item => {  
          passenger.push(new Passenger(item.name, item.sex, item.idNumber, item.phone));  
          // console.log(passenger);
        });  
    })
}
let city=ref<string[]>([]);
function getCity(airport:string){
  const params={
    aName:airport
  }
  // console.log(params)
  axios.get('http://localhost:8080/city',{params})
  .then((response)=>{
    // console.log(response.data.data[0]);
    city.value.push(response.data.data[0]);
  })
}
let detal=ref<FlightTransfer>();
async function open(t){
  // console.log(t)
  dialogVisible1.value=true;
  detal.value=tickets[t.index];
  // console.log(tickets[t.index]);
  city.value=[];
  for (const flightTransfer of detal.value.rows) {
    // console.log(flightTransfer.flight.arriveAirport);
    await getCity(flightTransfer.flight.arriveAirport);  // 等待 getCity 完成
  }
  // console.log(city.value)；
}
function beforeClose(){
  dialogVisible.value = false; 
  selectedPassenger.value=[];
  seat.value=0;
}
function f4(){
  router.push({
    name:'select',
    query:{
      order:JSON.stringify(data),
      account:route.query.account
    }
  });
}
function f5(){
  router.push({
    name:'select1',
    query:{
      order:JSON.stringify(data),
      account:route.query.account
    }
  });
}
//排序函数
watch(() => sort.value, (newValue) => {  
      tickets.splice(0, tickets.length, ...sortTickets(newValue));
      // console.log(tickets); 
    });
function sortTickets(seat: number): FlightTransfer[] {  
  const tripData = tickets.map(ticket => {  
    const totalPrice = ticket.rows.reduce((acc, row) => acc + row.flight.price, 0);  
    // 获取第一班航班的出发时间和最后一班航班的到达时间  
    const flights = ticket.rows.map(row => row.flight);  
    const startTime = flights[0].startTime; // 第一班航班的出发时间  
    const arriveTime = flights[flights.length - 1].arriveTime; // 最后一个航班的到达时间  
    // 计算总时间（以分钟为单位）  
    const totalDuration = (new Date(arriveTime).getTime() - new Date(startTime).getTime()) / (1000 * 60); // 转换为分钟  
    return { ticket, totalPrice, startTime, arriveTime, totalDuration }; // 返回每个旅行的信息  
  });  
  // 根据选择的排序方式进行排序  
  switch (seat) {  
    case 1:  
      // 时间最短：按总时间升序排序  
      tripData.sort((a, b) => a.totalDuration - b.totalDuration);  
      break;  
    case 2:  
      // 价格最低：按旅行总价格升序排序  
      tripData.sort((a, b) => a.totalPrice - b.totalPrice);  
      break;  
    case 3:  
      // 时间最长：按总时间降序排序  
      tripData.sort((a, b) => b.totalDuration - a.totalDuration);  
      break;  
    case 4:  
      // 价格最高：按旅行总价格降序排序  
      tripData.sort((a, b) => b.totalPrice - a.totalPrice);  
      break;  
    default:  
      break;  
  }  
  return tripData.map(item => item.ticket);  
}  
let nowIndex=ref<number>(0);
function buy(t){
    // console.log(t);
    dialogVisible.value = true;
    tableData1.value = [];
    tableData1.value.push({
      airlineCompany:t.startAirlineCompany as string,
      airlineName:t.startFlightName as string,
      startTime:t.firstFlightTime as string,
      arriveTime:t.lastFlightTime as string,
      startAirport:t.startAirport as string,
      arriveAirport:t.endAirport as string,
      price:t.totalPrice
    });
    nowIndex.value=t.index;
}
function extractTime(isoString:string) {  
  // 创建一个 Date 对象  
  const date = new Date(isoString);  
  // 获取小时和分钟  
  const hours = String(date.getUTCHours()).padStart(2, '0'); // 获取小时并补零  
  const minutes = String(date.getUTCMinutes()).padStart(2, '0'); // 获取分钟并补零  
  // 返回格式化的时间字符串  
  return `${hours}:${minutes}`;  
}  
function calculateTimeDifference(startIso: string, endIso: string): string {  
  // 将 ISO 字符串转换为 Date 对象  
  const startDate: Date = new Date(startIso);  
  const endDate: Date = new Date(endIso); 
  // 确保日期有效  
  if (isNaN(startDate.getTime()) || isNaN(endDate.getTime())) {  
    throw new Error('无效的日期格式');  
  }  
  // 计算时间差（以毫秒为单位）  
  const timeDifference: number = endDate.getTime() - startDate.getTime(); // 结果是毫秒  
  // 将时间差转换为小时和分钟  
  const totalMinutes: number = Math.floor(timeDifference / (1000 * 60)); // 转换为分钟  
  const hours: number = Math.floor(totalMinutes / 60); // 计算小时  
  const minutes: number = totalMinutes % 60; // 计算分钟  
  // 返回格式化的字符串  
  if(hours==0)
    return `${minutes}分钟`;
  else if(minutes==0)
    return `${hours}小时`;
  else
    return `${hours}小时${minutes}分钟`;  
}  
function getWeekday(selectedDate) {  
    // 注意：月份是从0开始的，所以需要减去1  
    const date = new Date(selectedDate);  
    // 获取星期几，0表示周日，1表示周一，依此类推  
    const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];  
    const weekdayIndex = date.getDay();  
    return weekdays[weekdayIndex];  
} 
</script>

<style>
.select1{
  display: flex;         /* 使容器为flexbox */  
  flex-direction: column; /* 垂直排列 */ 
}
.header {  
  display: flex;                /* 使el-header为flexbox布局 */  
  justify-content: flex-start;  /* 左对齐 */  
  align-items: center;          /* 垂直居中对齐 */  
}  
.el-menu {  
  flex-grow: 1; /* 使菜单项占据剩余空间 */  
}  
.aligned-title {  
  margin: 0; /* 清除外边距 */  
  padding-left: 20px; /* 可根据需要调整与菜单的距离 */  
}  
/* 增加一个活跃状态的样式 */  
.el-menu .el-menu-item.active {  
  color: aqua;   
}  
.buyButton{
    background-color: aqua !important; 
    color: white !important;
}
.no-border-table .el-table__header th {  
  border: none !important;  
}  
.demo-form-inline .el-select {
  --el-select-width: 200px;
}
.image-button-container {  
  display: flex; /* 使用 flexbox 布局 */  
  flex-direction: column; /* 垂直方向排列 */  
  align-items: center; /* 水平居中对齐 */  
  justify-content: center; /* 垂直居中对齐 */  
  height: 100%; /* 使容器高度适应表格单元格 */  
}  
.image-button-container img {  
  max-width: 100%; /* 图片自适应宽度 */  
  height: auto; /* 高度自适应，保持纵横比 */  
  margin-bottom: 10px; /* 图片与按钮之间的间距 */  
}  
</style>